﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
using Steve.UI.Site;
using System.Text;

namespace Steve.UI
{
    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString LabelEditorFor<T, TValue>(this HtmlHelper<T> html, Expression<Func<T, TValue>> expression, bool colSpan = false)
        {
            var div = new TagBuilder("div");

            if (colSpan) div.MergeAttribute("class", "col-span");

            div.InnerHtml +=
                html.LabelFor(expression).ToHtmlString() +
                html.EditorFor(expression).ToHtmlString();

            return MvcHtmlString.Create(div.ToString());
        }

        public static MvcHtmlString EditorForModel(this HtmlHelper html, string[] excludeProperties)
        {
            return html.EditorForModel(new { excludeProperties = excludeProperties });
        }

        public static MvcHtmlString NestedUnorderedList<T>(this HtmlHelper html, IEnumerable<T> list, Func<T, IEnumerable<T>> getChildren, Func<T, string> getDisplay)
        {
            return NestedUnorderedList(html, list, getChildren, item => MvcHtmlString.Create(html.Encode(getDisplay(item))));
        }

        public static MvcHtmlString NestedUnorderedList<T>(this HtmlHelper html, IEnumerable<T> list, Func<T, IEnumerable<T>> getChildren, Func<T, MvcHtmlString> getDisplay)
        {
            var sb = new StringBuilder();

            if (list.Any())
            {
                NestedUnorderedListHelper(html, sb, list, getChildren, getDisplay);
            }

            return MvcHtmlString.Create(sb.ToString());
        }

        private static void NestedUnorderedListHelper<T>(this HtmlHelper html, StringBuilder sb, IEnumerable<T> list, Func<T, IEnumerable<T>> getChildren, Func<T, MvcHtmlString> getDisplay)
        {
            sb.Append("<ul>");

            foreach (var item in list)
            {
                sb.Append("<li>");
                sb.Append(getDisplay(item));

                var children = getChildren(item);

                if (children.Any())
                {
                    NestedUnorderedListHelper(html, sb, children, getChildren, getDisplay);
                }

                sb.Append("</li>");
            }

            sb.Append("</ul>");
        }
    }
}